package org.example.ws;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonNull;
import com.sage.toolkit.gson.GsonUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Set;

import static org.example.ws.StringConstants.*;

public class ChatWebSocketHandler extends AbsChatWebSocketHandler {
    private final int maxUserInRoom;

    public ChatWebSocketHandler(int maxUserInRoom) {
        this.maxUserInRoom = maxUserInRoom;
    }

    @Override
    protected int getMaxUserInRoom() {
        return maxUserInRoom;
    }

    @Override
    protected void afterRoomJoined(WebSocketSession session) {
        this.emitUserSet(JOINED_TYPE, session);
        this.to(session).emit(INVITE_TYPE, this.getUser(session));
    }

    @Override
    protected void afterRoomLeaved(WebSocketSession session) {
        this.emitUserSet(LEAVED_TYPE, session);
    }

    private void emitUserSet(String type, WebSocketSession session) {
        Object room = this.getRoom(session);
        Object user = this.getUser(session);
        ChatRoom chatRoom = this.to(room);
        Set<Object> userSet = chatRoom.convertSessionSet(this::getUser);
        chatRoom.emit(type, userSet, user);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        JsonArray args = GsonUtils.fromJsonToArray(message.getPayload());
        JsonElement sendToUser = args.size() == 3 ? args.remove(2) : JsonNull.INSTANCE;
        JsonElement sender = (JsonElement) this.getUser(session, true);
        args.add(sender);
        message = new TextMessage(args.toString());
        if (!sendToUser.isJsonNull()) {
            this.sendToUser(message, sendToUser);
            return;
        }

        super.handleTextMessage(session, message);
    }
}
